<?php
/**
 * 相册管理
 * power by huanran.zhao
 * QQ: 523994553
 * 2012-07-17
 */
class PhotoApp extends CommonApp{

	private $filename;

	function indexAct() {
		//搜索条件
		$where="1 ";
		$title = I('get.title');
		if($title!='') {
			$where .= "AND `title` like '%{$title}%' ";
		}
		if(My::arr2var($_GET,'publish')==1) 	$publish.="AND `publish`=1 ";//已发布
		elseif(My::arr2var($_GET,'publish')==2) $publish.="AND `publish`=0 ";//未发布
		else $publish = '';//默认
		//指定相册唯一名称
		$item = I('get.item','photo');
		//取几级子分类
		$level = My::is_id(My::arr2var($_GET,'level'))?$_GET['level']:1;
		$soncat = M('category')->item2level($item,array('level'=>$level));//第2个级别
		$temp_ = My::arr2one($soncat,'id');//将数组中的某元素组合成一维数组(数组,2维,取id字段) 
		//sql的id范围IN条件
		if(is_array($temp_) AND $temp_) $where .= "AND `id` IN(".implode(',',$temp_).") ";
		else $where .= "AND 0 ";
		
		$result = DB('category')->where("{$where} {$publish}")->order("`ordering` ASC,`id` DESC")->cache()->select();
		//echo DB('')->getLastSql();
		//print_r($result);
		$all_num=0;//图片总数
		if(is_array($result))
		foreach($result as $key=>$value){
			$result[$key]['count'] = DB('photo')->where("`item`='{$value['item']}'")->cache()->count();
			$all_num+=$result[$key]['count'];//总图片数
		}
		//assign
		$this->assign('all_num',$all_num);//总图片数
		$this->assign('result',$result);
		$this->display();
	}
	
	function listAct() {	//index:图片列表  category:图片分类
		/******搜索条件 S******/
		$where="1 ";
		$title = I('get.title');
		if($title!='') {
			$where.="AND `title` like '%{$title}%' ";
		}
		$item = My::arr2var($_GET,'item');
		if(!My::is_item($item))
			$this->ajaxReturn(404,'相册ID错误!');
		$where.="AND `item`='{$item}' ";
		if(My::arr2var($_GET,'publish')==1) 	$publish = "AND `publish`=1 ";//已发布
		elseif(My::arr2var($_GET,'publish')==2) $publish = "AND `publish`=0 ";//未发布
		else $publish = '';//default
		$this->assign('publish',array(1=>'发布',2=>'不发布'));
		/******搜索条件 E******/
		
		$page = My::page(DB('photo')->where("$where $publish")->cache()->count());

		$result= DB('photo')->where("{$where} {$publish}")->order("`ordering` ASC,id DESC")->limit($page['limits'])->cache()->select();
		if(is_array($result))
		foreach($result as $key=>$value){//处理得到所在地
			$result[$key]['thumbs_link']=file_exists('thumbs/'.$value['link'])?'thumbs/'.$value['link']:$value['link'];
			$result[$key]['params']=My::decodeJson($value['params']);
		}

		//echo "<pre>";print_r($result);
		$this->assign('sql',urlencode("select `id` from `#__photo` where {$where} $publish ORDER BY `ordering` ASC,id DESC limit {$page['limits']}"));
		$this->assign('result',$result);
		$this->assign('page',$page);
		$this->display();
	}

	//编辑图片信息
	function modifyAct(){
		$id = My::arr2var($_GET,'id');
		if(My::is_id($id)){
			$result = DB('photo')->where("id={$id}")->find();
			//print_r($result);
			$this->assign("result",$result);
			$this->display();
		}else{
			echo "参数错误!";
		}
	}
	//保存编辑
	function saveAct(){
		$id = My::arr2var($_POST,'id');
		if(My::is_id($id)){
			DB('photo')->save($_POST);
		}
		header('Content-Type:text/html;charset=utf-8');
		echo "<script>alert('操作成功');parent.$.fn.colorbox.close();</script>";
	}
	
	/**
	 * 插入图片(图片列表页面)
	 */
	function insertAct(){
		//确定相册唯一名称
		$cat_id = I('get.cat_id',0);
		if(My::is_id($cat_id))
			$item = M('category')->id2item($cat_id);
		if(empty($item) OR !My::is_item($item))
			$item = My::arr2var($_GET,'item');
		if(!My::is_item($item))
			$this->ajaxReturn(404,'找不到相册分类ID');
		//where
		$where = "publish=1 ";
		//有table参数时
		if(My::is_var(My::arr2var($_GET,'table'))){
			$table = $_GET['table'];
			$where .= "AND `table`='{$table}' ";
		}
		//有idid参数时
		if(My::is_id(My::arr2var($_GET,'idid'))){
			$idid = $_GET['idid'];
			$where .= "AND `idid`='{$idid}' ";
		}
		//item
		$where .= "AND `item`='{$item}' ";
		$page = My::page(DB('photo')->where($where)->cache()->count(),array('buttonNum'=>5,'header'=>'<span class="rows">共%TOTAL_ROW%条 %NOW_PAGE%/%TOTAL_PAGE%页</span>','theme'=>'%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%'));
		$result = DB('photo')->where($where)->order("`ordering` ASC,adddate DESC,id DESC")->limit($page['limits'])->cache()->select();
		if(is_array($result))
		foreach($result as $key=>$value){
			if(file_exists('thumbs/'.$value['link'])) $result[$key]['src']='thumbs/'.$value['link'];//缩略图存在时;
			else $result[$key]['src'] = __PUB__.$value['link'];//缩略图不存在时用原图代替缩略图;
		}
		$this->assign('result',$result);
		$this->assign('page',$page);
		//print_r($result);
		//标题
		$this->assign('catname',My::item2field('category',$item,'title'));
		$this->display();
	}

	//插入/选择附件
	function insert_fileAct(){
		//确定相册唯一名称
		$item = My::arr2var($_GET,'item');
		if(!My::is_item($item))
			$this->ajaxReturn(404,'找不到item分类');
		//where
		$where = "publish=1 ";
		//item
		$where .= "AND `item`='{$item}' ";
		$page = My::page(DB('photo')->where($where)->cache()->count(),array('buttonNum'=>5, 'header'=>'<span class="rows">共%TOTAL_ROW%条 %NOW_PAGE%/%TOTAL_PAGE%页</span>', 'theme'=>'%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%'));
		$result = DB('photo')->where($where)->order("`ordering` ASC,adddate DESC,id DESC")->limit($page['limits'])->cache()->select();
		if(is_array($result))
		foreach($result as $key=>$value){
			if(file_exists('thumbs/'.$value['link'])) $result[$key]['src']='thumbs/'.$value['link'];//缩略图存在时;
			else $result[$key]['src'] = __PUB__.$value['link'];//缩略图不存在时用原图代替缩略图;
			$result[$key]['params'] = My::decodeJson($result[$key]['params']);
		}
		$this->assign('result',$result);
		$this->assign('page',$page);
		//print_r($result);
		//标题
		$this->assign('catname',My::item2field('category',$item,'title'));
		$this->display();
	}

	/**
	 * plupload插件,第三版本
	 */
	function pluploadAct(){
		set_time_limit(0);
		$item = My::arr2var($_GET,'item');
		if(!My::is_item($item))
			$this->ajaxReturn(404, '未选中任何相册!');
		include_once(PUB_DIR."share/plug/plupload/index.php");
	}
	/**
	 * plupload插件,保存图片并记录数据库
	 */
	function pluploadSaveAct(){
		set_time_limit(0);
		$item = My::arr2var($_GET,'item');
		if(!My::is_item($item))
			$this->ajaxReturn(404, '未选中任何相册!');
		include_once(PUB_DIR."share/plug/plupload/my.class.php");
		include_once(PUB_DIR."share/plug/plupload/upload.php");
	}

	function save_orderAct(){//save the order
		//echo "<pre>"; print_r($_POST);exit;
		if(My::arr2var($_POST,'order')!='') $order = explode('|',My::arr2var($_POST,'order'));
		if(is_array($order)){
			foreach($order as $key=>$value){
				if(My::is_id($value) AND $key>=0)
				DB('category')->where("id={$value}")->save(array('ordering'=>$key));
			}
		}
	}

	function delete_categoryAct(){//删除相册
		//echo "<pre>"; print_r($_GET);exit;
		$item = My::arr2var($_GET,'item');
		if(!My::is_item($item))
			$this->ajaxReturn(404,'相册ID错误');
		$num = DB('photo')->where("`item`='{$item}'")->count();;
		if($num==0)	{
			$ok = DB('category')->where("`item`='{$item}'")->clear()->delete();
			if($ok)
				$this->ajaxReturn(200, '删除成功!');
			else
				$this->ajaxReturn(300, '删除失败!');
		}
		else $this->ajaxReturn(300, '删除失败, 不能删除含有相片的相册!');
	}
	

	function save_image_orderAct(){
		//echo "<pre>"; print_r($_POST);exit;
		if(My::arr2var($_POST,'order')!='') $order = explode('|', My::arr2var($_POST,'order'));
		$pageSize = (isset($_SESSION['page_number']) AND My::is_id($_SESSION['page_number']))?$_SESSION['page_number']:10;
		if(is_array($order)){
			foreach($order as $key=>$value){
				if(My::is_id($value) AND $key>=0){
					$key=$pageSize*((intval(My::arr2var($_POST,'page')))-1)+$key;
					DB('photo')->where("id={$value}")->save(array('ordering'=>$key));
				}
			}
			//////重新定义前面所有页面的排序S
			//echo $_POST['sql'];exit;
			$query = urldecode(My::arr2var($_POST,'sql'));
			$list = DB('')->query($query);
			if(is_array($list) AND $list){
				foreach($list as $key=>$value){
					DB('photo')->where("id='{$value['id']}'")->save(array('ordering'=>$key));
				}
			}
			//////重新定义前面所有页面的排序E
		}
	}

	function deleteAct(){//删除数据
		//echo "<pre>"; print_r($_POST);exit;
		$id = My::arr2var($_GET,'id');
		if(isset($_POST['check_id']) AND is_array($_POST['check_id']) && count($_POST['check_id'])>0){//数组
			foreach($_POST['check_id'] as $key=>$value){
				if(My::is_id($value)){
					$temp_ = DB('photo')->field('link')->where("`id`={$value}")->find();
					$table = My::arr2var($_POST,'table');
					if(!My::is_table($table))
					    $this->ajaxReturn(300, "数据表不存在({$table})!");
					DB($table)->where("id={$value}")->clear()->delete();
					if(file_exists(PUB_DIR.$temp_['link']))		unlink(PUB_DIR.$temp_['link']);
					//if(file_exists(DATA_DIR.'thumbs/'.$temp_['link']))@unlink(DATA_DIR.'thumbs/'.$temp_['link']);//因为缩略图有后缀名,删除不了
				}
			}
			$this->ajaxReturn(200, '删除成功!');
		}elseif(My::is_id($id)){//单个id
			$temp_ = DB('photo')->field('link')->where("id={$id}")->find();
			$ok = DB('photo')->where("id={$id}")->clear()->delete();
			if($ok) {
				if(file_exists(PUB_DIR.$temp_['link'])) 	unlink(PUB_DIR.$temp_['link']);
				//if(file_exists(DATA_DIR.'thumbs/'.$temp_['link'])) 	@unlink(DATA_DIR.'thumbs/'.$temp_['link']);//因为缩略图有后缀名,删除不了
				$this->ajaxReturn(200, '删除成功!');
			}else{
				$this->ajaxReturn(300, '删除失败!');
			}
		}else{
			$this->ajaxReturn(300, '参数错误!');
		}
	}
	
	
	/**
	 * 生成缩略图
	 */
	public function thumbnailAct(){
		set_time_limit(0);
		$file = DATA_DIR.'thumbnail/thumbnail.php';//缩略图路径
		$exist = file_exists($file);//缩略图生成的指令文件是否存在
		$this->assign('exist',$exist);
		//进度条所需参数: page pagesize
		$page = My::is_id(My::arr2var($_GET,'page'))?$_GET['page']:0;;
		$pagesize= 10;
		
		$path = I('get.path');
		if($path){//有指定新路径时,生成thumbnail.php指令文件
			if($exist) unlink($file);//删除文件
			//扫描
			//self::scandir(DATA_DIR.'images');//指定目录
			self::scandir( iconv('utf-8','gb2312',$path) );//指定目录
			//生成thumbnail.php指令文件
			if(is_array($this->filename))	F('thumbnail',$this->filename,DATA_DIR.'/thumbnail/');//!!!!
		}elseif($exist){//如果指令文件存在,读取指令文件
			$this->filename = include($file);
		}

		if($page>0){
			$result['logs'] = '';
			if(is_array($this->filename))
			foreach($this->filename as $key=>$value){
				if($key>=$pagesize*($page-1) AND $key<($pagesize*($page-1)+$pagesize)){
				$imgs = Image::thumb($value,DATA_DIR.'/thumbnail','',700,700);//(源图片路径,缩略图存放路径,图片类型,宽,高)
				$result['logs'] .= '<br>生成成功：'.iconv('','utf-8',$value);
				}
			}
			$result['page'] = $page;
			$result['rate'] = ($pagesize*($page-1)+$pagesize)*100/count($this->filename);
			if($result['rate']>=100) {$result['rate']=100;$result['page']=0; }//百分比超过100时,说明程序已经执行完毕,100%,页数清0
			echo json_encode($result);
			exit;
		}else{
			$this->display();
		}
		
	}

	
	function scandir($pathname){
		//$files = glob("*.{php,txt,js,htm}",GLOB_BRACE);
		foreach(glob($pathname) as $filename )
		{
			if(is_dir($filename)) {self::scandir($filename.'/*');}//目录时
			else {
				//if(strpos($filename,"php")!==FALSE OR strpos($filename,"js")!==FALSE)//只匹配php和js文件
				$this->filename[] = $filename;//iconv('','utf-8',$filename);
			}
		}
	}
	
	//清理相册中不存在的图片
	public function clearAct(){
		$cfgUrl = C('admin|website_url');
		if(empty($cfgUrl))
			$this->ajaxReturn(300,'找不到正确的当前环境URL(admin|website_url参数)');
		$url = "http://".$_SERVER ['HTTP_HOST'];
		if(substr($cfgUrl,0,strlen($url))!=$url)
			$this->ajaxReturn(300,'与指定环境不匹配,不能进行清理操作! (admin|website_url参数)');
		$item = I('get.item');
		if(!My::is_item($item))
			$this->ajaxReturn(300,'相册名称item有误！');
		//开始
		$str = '';$num=0;
		//数据库中有数据,但实际文件被删除
		$result = DB('photo')->where("item='{$item}'")->field('id,link')->select();
		if(is_array($result))
		foreach($result as $value){
			if(!file_exists(PUB_DIR.$value['link'])){
				//删除该图片相应的所有缩略图
				$temp = glob(DATA_DIR.'thumbnail/'.$value['link']."_*",GLOB_BRACE);
				if(is_array($temp))  foreach($temp as $v)  if(file_exists($v))  unlink($v);
				//操作文字记录
				$str .= '<br>'.iconv('','utf-8',$value['link']); $num++;
				//删除数据库
				DB('photo')->where("id='{$value['id']}'")->clear()->delete();
			}else{//记录存在的有效图片列表
				$exists[]=$value['link'];
			}
		}
		//删除文件夹中的无家可归图片(当前应用)
		$allFileList = glob(PUB_DIR."share/images/{$item}/*");
		foreach($allFileList as $value){
			if(!in_array(str_replace(PUB_DIR,'',$value),$exists)){
				unlink($value);//删除不在数据库中的无家可归图片
				$str .= '<br>'.iconv('','utf-8',$value); $num++;
			}
		}
		$this->ajaxReturn(200,"成功删除无用的图片{$num}个 {$str}");
	}

}